<?php

namespace App\Api\Controllers\v1;

use App\Http\Controllers\ApiController;
use App\Http\Library\WeChat\MiniWeChat;
use App\Http\Requests\PayMoneyRequest;
use App\Http\Requests\UserAddressRequest;
use App\Http\Requests\UserBankRequest;
use App\Http\Requests\UserCarRequest;
use App\Http\Response\ApiResponse;
use App\Models\Appraise;
use App\Models\Area;
use App\Models\Good;
use App\Models\GoodVisit;
use App\Models\Money;
use App\Models\PaymentOrder;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\UserBank;
use App\Models\UserCar;
use App\Models\UserCollect;;

use App\Models\UserMoney;
use App\Services\OrderService;
use Exception;
use Illuminate\Http\Request;
use hg\apidoc\annotation as Apidoc;

/**
 * 用户接口
 * @Apidoc\Group("user")
 */
class UserController extends ApiController
{

    /**
     * 用户个人资料
     * @Apidoc\Url("/api/v1/user")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id", type="string",require=false, desc="用户ID")
     * @Apidoc\Returned(ref="userInfo")
     */
    public function index(Request $request): ApiResponse
    {
        $id = $request->get("id",0);
        $user = $this->getUserInfo($id);
        return $this->response()->success("ok")->data(['userInfo'=>$user]);
    }

    /**
     * 获取海报图
     * @Apidoc\Url("/api/v1/user/poster")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("content", type="string", desc="内容详情")
     */
    public function poster(): ApiResponse
    {
        $user_id = $this->user_id;
        return $this->response()->data(User::makePoster($user_id));
    }



    /**
     * 用户车牌列表
     * @Apidoc\Url("/api/v1/user/cars")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id", type="string",require=false, desc="用户ID")
     * @Apidoc\Returned(ref="listItems")
     */
    public function cars(): ApiResponse
    {
        $user_id = $this->user->id;
        $items = UserCar::getList($user_id);
        $data['items'] = $items;
        return $this->response()->success("ok")->data($data);
    }

    /**
     * 添加与修改车牌信息
     * @Apidoc\Url("/api/v1/user/saveCar")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int",require=false, desc="ID值,修改传递", default="")
     * @Apidoc\Param("brand_id", type="int",require=true, desc="品牌ID", default="")
     * @Apidoc\Param("type", type="int",require=true, desc="车辆类型", default="0")
     * @Apidoc\Param("plate_number", type="string",require=true, desc="车辆类型", default="")
     * @Apidoc\Param("color", type="string",require=true, desc="车辆颜色", default="")
     * @Apidoc\Param("name", type="string",require=true, desc="联系人", default="")
     * @Apidoc\Param("phone", type="string",require=true, desc="联系电话", default="")
     * @Apidoc\Param("is_default", type="int",require=true, desc="是否默认;0=否,1=是", default="0")
     * @Apidoc\Returned("car", type="object", desc="车牌信息")
     */
    public function saveCar(UserCarRequest $request): ApiResponse
    {
        $params = $request->validated();
        if ($params){
            $user_id = $this->user->id;
            $plate_number = $params['plate_number'];
            $id = $request->post("id");
            if ($id){
                $userCar  = UserCar::whereId($id)->first();
                foreach ($params as $key=>$value){
                    $userCar->{$key} = $value;
                }
                $res = $userCar->save();
            }else{
                $res = $id = UserCar::updateOrCreate($params,["plate_number"=>$plate_number,"user_id"=>$user_id]);
            }
            if ($res){
                $car = UserCar::find($id);
                return $this->response()->success("保存成功!")->data(['car'=>$car]);
            }else{
                return $this->response()->error("保存失败!");
            }
        }
        return $this->response()->error("参数请求错误!");
    }


    /**
     * 删除车牌信息
     * @Apidoc\Url("/api/v1/user/deleteCar/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id",type="string",desc="车牌ID")
     */
    public function deleteCar(): ApiResponse
    {
        $id = $this->request->route("id");
        $res = UserCar::query()->where("id",$id)->where("user_id",$this->user->id)->delete();
        return $this->response()->successIf($res,"删除成功")->errorIf(!$res,"删除失败");
    }

    /**
     * 设置默认车牌
     * @Apidoc\Url("/api/v1/user/saveDefaultCar/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id",type="string",desc="用户车牌ID")
     */
    public function saveDefaultCar(): ApiResponse
    {
        $id = $this->request->route("id");
        $row = UserCar::query()->where("id",$id)->where("user_id",$this->user->id)->first();
        $row->is_default = 1;
        $res = $row->save();
        if ($res!==false){
            return $this->response()->success("设置成功!");
        }else{
            return $this->response()->error("设置失败!");
        }
    }

    /**
     * 用户收货地址列表
     * @Apidoc\Url("/api/v1/user/address")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned(ref="listItems")
     */
    public function address(): ApiResponse
    {
        $user_id = $this->user->id;
        $items = UserAddress::query()->where("user_id",$user_id)->orderByDesc("is_default")->get();
        return $this->response()->success("ok")->data(['items'=>$items]);
    }

    /**
     * 添加与修改收货地址信息
     * @Apidoc\Url("/api/v1/user/saveAddress")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("name", type="string",require=true, desc="收件人姓名", default="")
     * @Apidoc\Param("phone", type="string",require=true, desc="联系电话", default="")
     * @Apidoc\Param("area", type="string",require=true, desc="所在地区", default="")
     * @Apidoc\Param("address", type="string",require=true, desc="详细地址",  default="")
     * @Apidoc\Param("is_default", type="int",require=true, desc="是否默认;0=否,1=是", default="0")
     * @Apidoc\Returned("address", type="object", desc="收货地址信息")
     */
    public function saveAddress(UserAddressRequest $request): ApiResponse
    {
        $params = $request->validated();
        $id = request()->input("id",0);
        if ($params){
            $params['user_id'] = $this->user->id;
            if ($id){
                $ua = UserAddress::whereId($id)->first();
            }else{
                $ua = new UserAddress;
            }
            foreach ($params as $field=>$value){
                $ua->{$field} = $value;
            }
            $res = $ua->save();
            if ($res){
                return $this->response()->success("保存成功!")->dataIf(!$id,['address'=>$ua->toArray()]);
            }else{
                return $this->response()->error("保存失败!");
            }
        }
        return $this->response()->error("参数请求错误!");
    }

    /**
     * 设置默认地址
     * @Apidoc\Url("/api/v1/user/saveDefaultAddress/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id",type="string",desc="地址ID")
     */
    public function saveDefaultAddress(): ApiResponse
    {
        $id = $this->request->route("id");
        $row = UserAddress::query()->where("id",$id)->where("user_id",$this->user->id)->first();
        $row->is_default = $row->is_default?0:1;
        $res = $row->save();
        if ($res!==false){
            return $this->response()->success("设置成功!");
        }else{
            return $this->response()->error("设置失败!");
        }
    }

    /**
     * 删除收货地址
     * @Apidoc\Url("/api/v1/user/delAddress/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id",type="string",desc="地址ID")
     */
    public function delAddress(): ApiResponse
    {
        $id = $this->request->route("id");
        $res = UserAddress::query()->where("id",$id)->where("user_id",$this->user->id)->delete();
        return $this->response()->successIf($res,"删除成功")->errorIf(!$res,"删除失败");
    }

    /**
     * 余额充值接口
     * @Apidoc\Url("/api/v1/user/payMoney")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require="true", desc="充值选项的ID", default="")
     * @Apidoc\Param(ref="paramLongLat")
     * @Apidoc\Returned(ref="payInfos")
     */
    public function payMoney(PayMoneyRequest $request){
        $params = $request->validated();
        return $this->wechatPay(function ($out_trade_no,$openid,$user_id) use ($params) {
            $id = $params['id'];
            $payMoney = Money::find($id);
            if (!$payMoney){
                throw new Exception("暂无此充值信息!");
            }
            if ($params['longitude']&&$params['latitude']){
                $area_id = Area::findAddress($params['longitude'],$params['latitude']);
                if ($area_id){
                    Money::getGivePrice($area_id, $payMoney);
                }
            }
            $amount = $payMoney->price;
            $extends = [
                'id'=>$payMoney->id,
                'price'=>$payMoney->price,
                'give_price'=>$payMoney->give_price
            ];
            OrderService::addMoneyOrder($user_id,$out_trade_no,$amount,$extends);
            $notify_url = route("api.v1.notify",['type'=>0]);
            return PaymentOrder::getPayData($openid,"充值余额",$out_trade_no,$amount,$notify_url);
        });
    }

    /**
     * 余额变动记录列表
     * @Apidoc\Url("/api/v1/user/moneyLogs")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("type", type="int", require="true", desc="类型:0=全部,1=收入,2=支出", default="0")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function moneyLogs(): ApiResponse
    {
        $user_id = $this->user_id;
        $data = UserMoney::getList($user_id);
        return $this->response()->data($data);
    }


    /**
     * 订单评价操作(可评价洗车与评价商品)
     * @Apidoc\Url("/api/v1/user/apprise")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("type", type="int", require="true", desc="类型:0=评价洗车,1=评价商品", default="0")
     * @Apidoc\Param("detail_id", type="int", require="true", desc="订单详情ID", default="")
     * @Apidoc\Param("score", type="int", require="true", desc="评分",  default="")
     * @Apidoc\Param("content", type="string", require="true", desc="评价内容",  default="")
     * @Apidoc\Param("images", type="array", require="true", desc="评价图片数组",  default="")
     */
    public function apprise(Request $request): ApiResponse
    {
        $detail_id = $request->input("detail_id");
        $score = $request->input("score");
        $content = $request->input("content");
        $type = $request->input("type");
        $images = $request->input("images");
        if (!$content){
            return $this->response()->error('请输入评价内容!');
        }
        $result = MiniWeChat::instance()->checkText($content);
        if ($result['errcode']){
            return $this->response()->error("评价内容文本含有敏感词信息!");
        }
        $params = [
            'type'=>$type,
            'user_id'=>$this->user_id,
            'detail_id'=>$detail_id,
            'score'=>$score,
            'content'=>$content,
            'images'=>$images,
        ];

        $res = Appraise::addApprise($params);
        if ($res){
            return $this->response()->success("已评价");
        }else{
            return $this->response()->error('评价失败!');
        }
    }

    /**
     * 收藏与取消收藏
     * @Apidoc\Url("/api/v1/user/collect/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id", type="int", require="true", desc="商品ID",  default="")
     * @Apidoc\Returned("is_collect", type="int", desc="是否已收藏,1=已收藏,0=已取消收藏")
     */
    public function collect(Request $request): ApiResponse
    {
        $good_id = $request->route("id");
        $good = Good::whereId($good_id)->first();
        if (!$good){
            return $this->response()->error("暂无此商品信息");
        }
        $map = ['user_id'=>$this->user_id, 'good_id'=>$good_id];
        $result = UserCollect::collect($map);
        if ($result['res']){
            if ($result['code']){
                return $this->response()->success("已取消收藏")->data(['is_collect'=>0]);
            }else{
                return $this->response()->success("已收藏")->data(['is_collect'=>1]);
            }
        }
        return $this->response()->error("提交失败");
    }

    /**
     * 收藏列表
     * @Apidoc\Url("/api/v1/user/collects")
     * @Apidoc\Method("GET")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function collects(): ApiResponse
    {
        $user_id = $this->user_id;
        $data = UserCollect::getList($user_id);
        return $this->response()->data($data);
    }

    /**
     * 浏览记录
     * @Apidoc\Url("/api/v1/user/visits")
     * @Apidoc\Method("GET")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function visits(): ApiResponse
    {
        $user_id = $this->user_id;
        $data = GoodVisit::getList($user_id);
        return $this->response()->data($data);
    }

    /**
     * 用户银行卡列表
     * @Apidoc\Url("/api/v1/user/banks")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("items",type="array",ref="App\Models\UserBank")
     */
    public function banks(): ApiResponse
    {
        $user_id = $this->user_id;
        $data = UserBank::getList($user_id);
        return $this->response()->success("ok")->data($data);
    }

    /**
     * 添加与修改用户银行卡
     * @Apidoc\Url("/api/v1/user/saveBank")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("bank_name", type="string",require=true, desc="开户行名称", default="")
     * @Apidoc\Param("bank_num", type="string",require=true, desc="银行卡号", default="")
     * @Apidoc\Param("name", type="string",require=true, desc="开户姓名", default="")
     * @Apidoc\Returned("banks", type="object", desc="银行卡信息")
     */
    public function saveBank(UserBankRequest $request): ApiResponse
    {
        $params = $request->validated();
        if ($params){
            $user_id = $this->user_id;
            $bank_num = $params['bank_num'];
            $exit = UserBank::query()->where("user_id","<>",$user_id)->where("bank_num",$bank_num)->exists();
            if ($exit){
                return $this->response()->error("此银行卡记录已存在!");
            }
            $res = UserBank::updateOrCreate($params,["bank_num"=>$bank_num,"user_id"=>$user_id]);
            if ($res){
                $banks = UserBank::find($res->id);
                return $this->response()->success("保存成功!")->data(['banks'=>$banks]);
            }else{
                return $this->response()->error("保存失败!");
            }
        }
        return $this->response()->error("参数请求错误!");
    }


    /**
     * 删除银行卡
     * @Apidoc\Url("/api/v1/user/deleteBank/:id")
     * @Apidoc\Method("POST")
     * @Apidoc\RouteParam("id",type="string",desc="车牌ID")
     */
    public function deleteBank(Request $request): ApiResponse
    {
        $id = $request->route("id");
        $res = UserBank::query()->where("id",$id)->where("user_id",$this->user_id)->delete();
        return $this->response()->successIf($res,"删除成功")->errorIf(!$res,"删除失败");
    }

    /**
     * 下级用户列表
     * @Apidoc\Url("/api/v1/user/child")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("id", type="int",require=true, desc="用户ID", default="")
     * @Apidoc\Returned("items",type="array",desc="用户列表")
     */
    public function child(Request $request): ApiResponse
    {
        $id = $request->input("id",0);
        $user_id = $id?:$this->user_id;
        $data = User::getChild($user_id);
        return $this->response()->success("ok")->data($data);
    }


}
